#include "mem_sal.h"






#if (CONFIG_MEM_STD_LIBRARY)

#ifdef __CC_ARM
/* avoid the heap and heap-using library functions supplied by arm */
#pragma import(__use_no_heap)
#endif

void *malloc(unsigned int n)
{
    // printf("std malloc\r\n");
    return mem_malloc(n);
}

void free(void *rmem)
{
    mem_free(rmem);
}

void *realloc(void *rmem, unsigned int newsize)
{
    return mem_realloc(rmem, newsize);
}

void *calloc(unsigned int nelem, unsigned int elsize)
{
    return mem_calloc(nelem, elsize);
}

#endif // CONFIG_MEM_STD_LIBRARY


/* debug */

#if (CONFIG_SHELL_ENABLE)

#include "shell.h"


int mem_test(int argc, char **argv)
{
    int i;
    void *(*func_malloc)(size_t);
    void (*func_free)(void *);
    char *p1, *p2;
    _mem_sal_info_t info;

    printf("mem_test start in [%s]\r\n", mem_get_name());
    if (argc > 2) return 0;
    func_malloc = mem_malloc;
    func_free = mem_free;
#if (CONFIG_MEM_STD_LIBRARY)
    if (argc == 2)
    {
        func_malloc = malloc;
        func_free = free;
        printf("func port using std\r\n");  
    }
#endif

    p1 = func_malloc(1024);
    p2 = func_malloc(1024);

    if (p1 == NULL || p2 == NULL)
    {
        printf("mem malloc fail!\r\n");
        goto _exit;
    }

    printf("p1 = 0x%08X\r\n", (uint32_t)p1);
    printf("p2 = 0x%08X\r\n", (uint32_t)p2);

    /* edit buf */
    printf("mem_test edit buf\r\n");
    for (i=0; i<1024; i++)
    {
        p1[i] = p2[i] = i & 0xFF;
    }

    /* check buf */
    printf("mem_test check buf\r\n");
    for (i=0; i<1024; i++)
    {
        if ((p1[i] != p2[i]) || (p1[i] != (i&0xFF)))
        {
            printf("mem check err in [%d]\r\n", i);
            break;
        }
    }

    printf("mem check ok!\r\n");
    mem_get_info(&info);
    printf("Mem HEAP: %12d%12d%12d\r\n",info.total, info.used, info.total-info.used);

_exit:
    func_free(p1);
    func_free(p2);

    printf("mem_test end\r\n");
    mem_get_info(&info);
    printf("Mem HEAP: %12d%12d%12d\r\n",info.total, info.used, info.total-info.used);

    return 0;
}
SHELL_CMD_EXPORT(mem_test, mem_test)

#endif  // CONFIG_SHELL_ENABLE for debug

